package com.ccp.dev.im.controller;

import com.alibaba.fastjson.JSONObject;
import com.ccp.dev.core.basic.consts.SystemConst;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.page.PageBean;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringPool;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.im.model.*;
import com.ccp.dev.im.server.constant.Constants;
import com.ccp.dev.im.service.*;
import com.ccp.dev.system.consts.FileManagementContants;
import com.ccp.dev.system.model.SysOrg;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.system.model.UserPosition;
import com.ccp.dev.system.service.SysFileService;
import com.ccp.dev.system.service.SysOrgService;
import com.ccp.dev.system.service.UserPositionService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 聊天管理控制器类
 *
 * @author y
 */
@Controller
@RequestMapping(UrlConstants.PROJECT_ROOT + UrlConstants.PROJECT_MODULE_IM)
public class ImController extends SysBaseController {
    @Resource
    private ImUserService imUserService;
    @Resource
    private SysOrgService sysOrgService;
    @Resource
    private UserPositionService userPositionService;
    @Resource
    private SysFileService sysFileService;
    @Resource
    private ImRoomService imRoomService;
    @Resource
    private ImFriendMessageService imFriendMessageService;
    @Resource
    private ImRoomMessageService imRoomMessageService;
    @Resource
    private ImRoomMsgStatusService imRoomMsgStatusService;
    @Resource
    private ImSystemMessageService imSystemMessageService;
    @Resource
    private ImRoomUserService imRoomUserService;

    /**
     * 主面板配置初始化
     *
     * @param request HttpServletRequest
     * @return String
     * @throws Exception Exception
     */
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/imIndex")
    public String imIndex(HttpServletRequest request, Model model) throws Exception {
        ImUser imUser = imUserService.getByUserId(ContextUtil.getCurrentUser().getUserId());
        model.addAttribute("currentUserId", imUser.getId());
        model.addAttribute("ctx", request.getContextPath());
        return "/imIndex";
    }


    /**
     * 主面板页面初始化
     *
     * @param response HttpServletResponse
     * @param request  HttpServletRequest
     * @return String
     * @throws Exception Exception
     */
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/demo")
    public String demoPage(HttpServletResponse response, HttpServletRequest request) throws Exception {
        return "/demo";
    }

    /**
     * 消息记录页面
     *
     * @param response HttpServletResponse
     * @param request  HttpServletRequest
     * @return String
     * @throws Exception Exception
     */
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/chatLog")
    public String chatLog(HttpServletResponse response, HttpServletRequest request, Model model) throws Exception {
        String type = RequestUtil.getString(request, "type");
        String id = RequestUtil.getString(request, "id");
        model.addAttribute("type", type);
        model.addAttribute("id", id);
        model.addAttribute("ctx", request.getContextPath());
        return "/functionPage/chatlog";
    }

    /**
     * 取得当前登录用户所拥有得分组以及好友
     *
     * @param response HttpServletResponse
     * @param request  HttpServletRequest
     * @return Object
     * @throws Exception Exception
     */
    @GetMapping("/mainPanelInit")
    @ResponseBody
    public Object mainPanelInit(HttpServletResponse response, HttpServletRequest request) throws Exception {
        JSONObject jsonObject = new JSONObject();
        SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
        String userId = sysUser.getUserId();
        ImUser imUser = imUserService.getByUserId(userId);
        if (StringUtils.isNotEmpty(imUser.getAvatar())) {
            imUser.setAvatar(request.getContextPath() + imUser.getAvatar());
        }
        Map<String, Object> map = new HashMap();
        map.put("receivUser", imUser.getId());
        map.put("isRead", ImSystemMessage.IS_READ_N);
        int count = imSystemMessageService.queryNotReadMsgNum(map);
        imUser.setMsgNum(count);
        imUser.setStatus(Constants.UserType.ONLINE);
        //当前登录人信息
        jsonObject.put("mine", imUser);
        List<SysOrg> sysOrgList = null;
/*        if (SystemConst.SUPER_ADMIN_ID.equals(userId)) {
            sysOrgList = sysOrgService.querySubSysOrgTreeDataBySupOrgId(SystemConst.TOP_ORG_ID);
        } else {
            SysOrg sysOrg = sysOrgService.getOrgByUserId(userId);
            String belongOrgId = sysOrg != null ? sysOrg.getOrgId() : SystemConst.TOP_ORG_ID;
            sysOrgList = sysOrgService.querySysOrgTreeDataByOrgId(belongOrgId);
        }*/
        //不管谁登陆先都查所有， 如果日后需要根据组织去过滤放开上边，注释下边一句
        sysOrgList = sysOrgService.queryOrgByPath(SystemConst.TOP_ORG_ID);
        if (sysOrgList != null) {
            sysOrgList.sort((o1, o2) -> {
                return o1.getCreateTime().compareTo(o2.getCreateTime());
            });
            List<ImGroup> imGroupList = new ArrayList<>();
            for (SysOrg sysOrg : sysOrgList) {
                List<ImUser> imUserList = new ArrayList<>();
                ImGroup imGroup = new ImGroup();
                imGroup.setId(sysOrg.getOrgId());
                imGroup.setGroupname(sysOrg.getOrgName());
                List<UserPosition> list = userPositionService.queryUserByOrgIds(sysOrg.getOrgId());
                for (UserPosition userPosition : list) {
                    ImUser iu = imUserService.getByUserId(userPosition.getUserId());
                    if (StringUtils.isNotEmpty(iu.getAvatar())) {
                        iu.setAvatar(request.getContextPath() + iu.getAvatar());
                    }
                    if (Constants.UserType.ONLINE.equals(iu.getStatus()) || iu.getId().equals(imUser.getId()) )  {
                        iu.setStatus(Constants.UserType.ONLINE);
                    } else {
                        iu.setStatus(Constants.UserType.OFFLINE);
                    }
                    imUserList.add(iu);
                }
                //如果是群聊的添加人员列表，需要把imUserList里面的人员过滤掉已经是这个群组的人员
                String roomId = RequestUtil.getString(request, "roomId");
                String type = RequestUtil.getString(request, "type");
                List<ImUser> retUserList = imUserService.getCurrentTreeUserList(imUserList,type, roomId,imUser.getId());
                imGroup.setList(retUserList);
                imGroupList.add(imGroup);
            }
            jsonObject.put("friend", imGroupList);
        }
        //查询群信息
        QueryFilter queryFilter = new QueryFilter(request, false);
        queryFilter.addFilter("userId", imUser.getId());
        List<ImRoom> groups = imRoomService.queryList(queryFilter);
        jsonObject.put("group", groups);
        return getResultDataSuccess("operation.success", jsonObject);
    }

    /**
     * 文件上传
     *
     * @param response HttpServletResponse
     * @param request  MultipartHttpServletRequest
     * @return Object
     * @throws Exception e
     */
    @PostMapping("/fileUpload")
    @ResponseBody
    public Object fileUpload(HttpServletResponse response, MultipartHttpServletRequest request) throws Exception {
        Map<String, Object> result = sysFileService.fileUpload(request, "", "", FileManagementContants.FILE_SECRET_PUBLIC);
        List<Map<String, Object>> fileList = (List<Map<String, Object>>) result.get("fileList");
        JSONObject jsonObject = new JSONObject();
        if (!fileList.isEmpty()) {
            jsonObject.put("src", request.getContextPath() + "/system/attachFile/download?fileId=" + fileList.get(0).get("fileId"));
            String fileName = fileList.get(0).get("fileName") + "." + fileList.get(0).get("extName");
            jsonObject.put("name", fileName);
        }
        return getResultDataSuccess("file.upload.success", jsonObject);
    }

    /**
     * 拉取离线消息
     *
     * @param response HttpServletResponse
     * @param request  MultipartHttpServletRequest
     * @return Object
     * @throws Exception e
     */
    @PostMapping("/getOfflineMsg")
    @ResponseBody
    public Object getOfflineMsg(HttpServletResponse response, HttpServletRequest request) throws Exception {
        String userId = ContextUtil.getCurrentUserId();
        ImUser imUser = imUserService.getByUserId(userId);
        JSONObject jsonObject = new JSONObject();
        List<ImFriendMessage> imFriendMessageList = imFriendMessageService.queryOfflineMsg(imUser.getId());
        jsonObject.put("friendMsg", imFriendMessageList);
        List<ImRoomMessage> imRoomMessageList = imRoomMessageService.queryOfflineMsg(imUser.getId());
        jsonObject.put("groupMsg", imRoomMessageList);
        return getResultDataSuccess("operation.success", jsonObject);
    }

    /**
     * 修改消息状态
     *
     * @param response HttpServletResponse
     * @param request  MultipartHttpServletRequest
     * @return Object
     * @throws Exception e
     */
    @GetMapping("/modifyReadStatus")
    @ResponseBody
    public Object modifyReadStatus(HttpServletResponse response, HttpServletRequest request) throws Exception {
        String[] id = RequestUtil.getStringAryByStr(request, "id");
        String type = RequestUtil.getString(request, "type");
        if (BeanUtils.isNotEmpty(id)) {
            if ("1".equals(type)) {
                //单聊
                imFriendMessageService.updateReadStatus(id);
            } else if ("2".equals(type)) {
                //群聊
                ImUser imUser = imUserService.getByUserId(ContextUtil.getCurrentUserId());
                imRoomMsgStatusService.delByRoomIdAndUserId(id[0], imUser.getId());
            } else if ("3".equals(type)) {
                //单聊 清所有  根据朋友得id 和我得id  去修改状态
                ImUser imUser = imUserService.getByUserId(ContextUtil.getCurrentUserId());
                imFriendMessageService.updateIsReadByFromIdAndToId(id[0], imUser.getId());
            }
        }
        return getResultDataSuccess("operation.success");
    }

    /**
     * 消息记录数据
     *
     * @param response HttpServletResponse
     * @param request  HttpServletRequest
     * @return Object
     * @throws Exception Exception
     */
    @GetMapping("/chatLogData")
    @ResponseBody
    public Object chatLogData(HttpServletResponse response, HttpServletRequest request) throws Exception {
        JSONObject jsonObject = new JSONObject();
        List<Map<String, Object>> mapArrayList = new ArrayList<>();
        QueryFilter queryFilter = new QueryFilter(request);
        PageBean pageBean = queryFilter.getPageBean();
        pageBean.setPagesize(10);
        queryFilter.setPageBean(pageBean);
        String type = RequestUtil.getString(request, "type");
        String id = RequestUtil.getString(request, "id");
        String findContent = RequestUtil.getString(request, "findContent");
        if (StringUtils.isNotEmpty(findContent)) {
            queryFilter.addFilter("findContent", StringPool.PERCENT + findContent + StringPool.PERCENT);
        }
        if (StringUtil.isNotEmpty(type) && StringUtil.isNotEmpty(id)) {
            ImUser imUser = imUserService.getByUserId(ContextUtil.getCurrentUserId());
            queryFilter.addFilter("userId", imUser.getId());
            if ("friend".equals(type)) {
                mapArrayList = imFriendMessageService.queryMsgByFromIdAndToId(queryFilter);
            } else if ("group".equals(type)) {
                mapArrayList = imRoomMessageService.queryMsgByRoomId(queryFilter);
            }
        }
        jsonObject.put("list", mapArrayList);
        jsonObject.put("pageBean", queryFilter.getPageBean());
        return getResultDataSuccess("operation.success", jsonObject);
    }
}
